from flask import jsonify, request
from app.libs.helper import is_isbn_or_key
from app.spider.yushu_book import YuShuBook
from . import web
from app.forms.book import SearchForm
# 视图函数
# @web.route('/book/search/<q>/<page>')
@web.route('/book/search')
def search():
  '''
    Request 查询参数 post参数
    Response
  '''
  # q = request.args['q']
  # page = request.args['page']

  # 验证层
  form = SearchForm(request.args)
  if form.validate():
    q = form.q.data.strip()
    page = form.page.data
    isbn_or_key = is_isbn_or_key(q)
    if isbn_or_key == 'isbn':
      result = YuShuBook.search_by_isbn(q)
    else:
      result = YuShuBook.search_by_keyword(q,page)
    return jsonify(result)
  else:
    return jsonify(form.errors)





'''
  flask 路由原理
    客户端  url  Search
    app.add_url_rule(url, view_func=, endpoint=)
'''


